package com.mriassl.rabbitmq.rpc;

import java.io.IOException;

import com.mriassl.rabbitmq.base.BaseConnection;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.AMQP.BasicProperties;
import com.rabbitmq.client.Consumer;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;

public class RPCServer extends BaseConnection {
	
	public RPCServer() throws Exception {
		init();
	}
	
	public void start() throws Exception {
		channel.queueDeclare(RPCConsts.RPC_QUEUE_NAME, false, false, false, null);
		channel.basicQos(1);
		Consumer consumer = new DefaultConsumer(channel) {
			@Override
			public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
				String correlationId = properties.getCorrelationId();
				String message = new String(body, "UTF-8");
				System.out.println("RPCServer received msg:"+message+" corelationId:"+correlationId);
				String response = "this is message from server, correlationId:"+correlationId;
				BasicProperties replyProps = new BasicProperties.Builder().correlationId(correlationId).build();
				channel.basicPublish("", correlationId, replyProps, response.getBytes("UTF-8")); 
			}
		};
		channel.basicConsume(RPCConsts.RPC_QUEUE_NAME, true, consumer);
	}
	
	
	public static void main(String[] args) throws Exception {
		RPCServer client = new RPCServer();
		client.start();
	}
	
}
